package com.sxfq.loansupermarket.backsystem.modular.refunds.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.TcInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.PaymentRecordInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.RechargeInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.SearchPaymentRecordInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.service.IPaymentRecordService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 *
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/paymentRecord")
public class PaymentRecordController extends BaseController {
    @Autowired
    IPaymentRecordService service;

    @Autowired
    ICustomerService customerService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/balance/";

    /**
     * 跳转到结账明细页面
     */
    @RequestMapping(value = "")
    public String recharge(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        if (ShiroKit.getSessionAttr("checkoutMethodsList") == null) {
            String sql = "select id,checkout_method as checkoutMethods from checkout_method_info;";
            List<PaymentRecordInfo> checkoutMethodsList=sqlMapper.selectList(sql,PaymentRecordInfo.class);
            ShiroKit.setSessionAttr("checkoutMethodsList", checkoutMethodsList);
        }
        model.addAttribute("checkoutMethodsList", ShiroKit.getSessionAttr("checkoutMethodsList"));
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("sttleAccountsTime", ShiroKit.getUser().getSttleAccountsTime());
        return PREFIX + "paymentRecord.html";
    }

    @RequestMapping(value = "/toUpdate/{ci}")
    public String toAddVisited(@PathVariable String ci, Model model) {
        String customerName = ci.split(",")[0];
        String id = ci.split(",")[1];
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String tableName = tableHead + "recharge_info";
        String sql = "select * from " + tableName + " where id='" + id + "' limit 0,1";
        PaymentRecordInfo paymentRecordInfo = sqlMapper.selectOne(sql, PaymentRecordInfo.class);
        if (paymentRecordInfo == null) {
            String sql2 = "select * from " + tableName + " where id=concat('" + id + "','.0') limit 0,1";
            paymentRecordInfo = sqlMapper.selectOne(sql2, PaymentRecordInfo.class);
        }
        if (ShiroKit.getSessionAttr("checkoutMethodList") == null) {
            String selectsqlCM = "select id,checkout_method as checkoutMethod from checkout_method_info where charge_bill_is_inCash=1 order by num ;";
            ShiroKit.setSessionAttr("checkoutMethodList", sqlMapper.selectList(selectsqlCM));
        }
        model.addAttribute("checkoutMethodList", ShiroKit.getSessionAttr("checkoutMethodList"));
        model.addAttribute("id", id);
        model.addAttribute("customerName", customerName);
        model.addAttribute("paymentRecordInfo", paymentRecordInfo);
        return PREFIX + "update_checkout_method.html";
    }



    @RequestMapping(value = "/updateCheckoutMethod", method = RequestMethod.POST)
    @ResponseBody
    public int updateCheckoutMethod(@RequestBody PaymentRecordInfo paymentRecordInfo) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "recharge_info";
        String sql2 = "select * from " + tableName + " where id='" + paymentRecordInfo.getId() + "' limit 1";
        RechargeInfo info = sqlMapper.selectOne(sql2, RechargeInfo.class);
        String sql1 ="select * from reservemoney_deal where deal_id ='"+paymentRecordInfo.getId()+"'";
        RechargeInfo info2 = sqlMapper.selectOne(sql1,RechargeInfo.class);
        String sql3 ="select * from reservemoney_orthodontics_deal where deal_id ='"+paymentRecordInfo.getId()+"'";
        RechargeInfo info3 = sqlMapper.selectOne(sql3,RechargeInfo.class);
        for(int i = 0;i<paymentRecordInfo.getChargingMethod().size();i++){
            Random rand = new Random();
            int randomNumber = rand.nextInt(999999);
            String id = randomNumber + info.getOperationTime();
            String id2="";
            String dealId="";
            String documentNumber="";
            String tcName="";
            if(info.getId2()==null || info.getId2() ==""){
                 id2="null";
            }else{
                id2="'"+info.getId2()+"'";
            }
            if(info.getDealId()==null || info.getDealId()==""){
                 dealId="null";
            }else{
                dealId="'"+info.getDealId()+"'";
            }
            if(info.getDocumentNumber()==null || info.getDocumentNumber()==""){
                 documentNumber="null";
            }else{
                documentNumber="'"+info.getDocumentNumber()+"'";
            }
            if(info.getTcName()==null || info.getTcName()==""){
                tcName="null";
            }else{
                tcName="'"+info.getTcName()+"'";
            }
            String insertSql = " INSERT INTO `" + tableName + "` (`id`, `status`, `customer_id`, `reservations_id`, " +
                   "  `recharge_people`,`checkout_method_id`,`checkout_method`, `document_number`,deal_id " +
                   " ,`actual_account_balance`, `recharge_time`, `operation_time`, " +
                   "  `remarks`, `is_record`, `id2`,deduction_amount,deduction_type,hospital_performance,section_performance,equation,tc_name,give_account_balance,account_arrears,recharges_time,isEarnes) values  " +
                   " ('" + id + "','"+info.getStatus()+"','" + info.getCustomerId() + "','" + info.getReservationsId() + "', " +
                   " '" + info.getRechargePeople()+"',(select id from checkout_method_info where checkout_method='" + paymentRecordInfo.getChargingMethod().get(i).getCheckoutMethod() + "'), " +
                   "'"+paymentRecordInfo.getChargingMethod().get(i).getCheckoutMethod()+"', "+ documentNumber + ", " + dealId + " ," +
                   "'" + paymentRecordInfo.getChargingMethod().get(i).getAmount() + "','" + info.getRechargeTime() + "', '" + info.getOperationTime() + "', '" + info.getRemarks() + "', " +
                   " '" + info.getIsRecord() + "',"+id2+", '" + info.getDeductionAmount() + "','" + info.getDeductionType() + "','" +paymentRecordInfo.getChargingMethod().get(i).getAmount()+ "'," +
                   "'"+paymentRecordInfo.getChargingMethod().get(i).getAmount()+"','"+info.getEquation()+"',"+tcName+",'"+info.getGiveAccountBalance()+"','"+info.getAccountArrears()+"','"+info.getRechargesTime()+"','"+info.getIsEarnes()+"')";
            sqlMapper.insert(insertSql);
            if(info2 !=null){
                String insertSql1 = " INSERT INTO reservemoney_deal (`actual_account_balance`, `checkout_method`, `is_do`, " +
                        "  `checkout_method_id`,`recharge_time`,`operation_time`, `status`,mode " +
                        " ,`reservations_id`, `customer_id`, `deal_id`, " +
                        "  `tc_name`, `recharge_people`, `add_store`,is_record,remarks) values  " +
                        " ('"+paymentRecordInfo.getChargingMethod().get(i).getAmount()+"','" + paymentRecordInfo.getChargingMethod().get(i).getCheckoutMethod() + "','" + info2.getIsDo() + "', " +
                        " (select id from checkout_method_info where checkout_method='" + paymentRecordInfo.getChargingMethod().get(i).getCheckoutMethod() + "'), " +
                        "'"+info2.getRechargeTime()+"', '"+ info2.getOperationTime() + "', '" + info2.getStatus() + "' ," +
                        "'" + info2.getMode()+ "','" + info2.getReservationsId() + "', '" + info2.getCustomerId() + "', '" + info2.getDealId() + "', " +
                        " '" + info2.getTcName()+ "','"+info2.getRechargePeople()+"', '" + info2.getAddStore() + "','" + info2.getIsRecord() + "','" + info2.getRemarks()+ "')";
                sqlMapper.insert(insertSql1);
            }
            if(info3 !=null){
                String insertSql2 = " INSERT INTO reservemoney_orthodontics_deal (`actual_account_balance`, `checkout_method`, `is_do`, " +
                        "  `checkout_method_id`,`recharge_time`,`operation_time`,end_time, `status`,mode " +
                        " ,`reservations_id`, `customer_id`, `deal_id`, " +
                        "  `tc_name`, `recharge_people`, `add_store`,is_record,remarks) values  " +
                        " ('"+paymentRecordInfo.getChargingMethod().get(i).getAmount()+"','" + paymentRecordInfo.getChargingMethod().get(i).getCheckoutMethod() + "','" + info3.getIsDo() + "', " +
                        " (select id from checkout_method_info where checkout_method='" + paymentRecordInfo.getChargingMethod().get(i).getCheckoutMethod() + "'), " +
                        "'"+info3.getRechargeTime()+"', '"+ info3.getOperationTime() + "', '"+info3.getEndTime()+"','" + info3.getStatus() + "' ," +
                        "'" + info3.getMode()+ "','" + info3.getReservationsId() + "', '" + info3.getCustomerId() + "', '" + info3.getDealId() + "', " +
                        " '" + info3.getTcName()+ "','"+info3.getRechargePeople()+"', '" + info3.getAddStore() + "','" + info3.getIsRecord() + "','" + info3.getRemarks()+ "')";
                sqlMapper.insert(insertSql2);
            }
        }
        String deleteSql = "delete  from "+tableName+" where id='"+paymentRecordInfo.getId()+"'";
        sqlMapper.delete(deleteSql);
        if(info2 !=null){
            String deleteSql1 = "delete  from reservemoney_deal where id='"+info2.getId()+"'";
            sqlMapper.delete(deleteSql1);
        }
        if(info3 !=null){
            String deleteSql2 = "delete  from reservemoney_orthodontics_deal where id='"+info3.getId()+"'";
            sqlMapper.delete(deleteSql2);
        }
        return 1;
    }

    /**
     * 结账明细列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object rechargeList(SearchPaymentRecordInfo info) {
        if(info.getAbbreviation() == null || info.getAbbreviation() =="" || info.getAbbreviation() =="null"){
            return null;
        }else{
            Page<PaymentRecordInfo> page = new PageFactory<PaymentRecordInfo>().defaultPage();
            try {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<PaymentRecordInfo> list = service.selectPageListInfo(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListInfo(page, info);
                }
                page.setTotal(service.getQueryPagesCount(page, info));
                page.setRecords(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.packForBT(page);
        }
    }

    @RequestMapping("/sumBorrowAmount")
    @ResponseBody
    public HashMap sumBorrowAmount(@RequestParam(required = false) String checkoutMethod,
                                   @RequestParam(required = false) String reach,
                                   @RequestParam(required = false) String fieldTc,
                                   @RequestParam(required = false) String doctor,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String customerStatus,
                                   @RequestParam(required = false) String endTime) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName1 = tableHead + "recharge_info";
        String sql = "select sum(t1.actualAccountBalance) as borrowAmount_sum from (select t1.id as id,t1.customer_id as customerId ,t1.record_people as recordPeople, " +
                " t1.reservations_id as reservationsId,t1.operation_time as operationTime,t1.checkout_method as checkoutMethod,t1.recharge_time as rechargeTime, " +
                " t1.remarks as remarks , t2.customer_name as customerName ,t2.customer_phone as customerPhone,t2.doctor as doctor, " +
                " t1.record_time as recordTime,t1.actual_account_balance as actualAccountBalance, t2.customer_status as customerStatus, " +
                " t2.customer_sex as customerSex ,t2.customer_age as customerAge,t2.field_tc as fieldTc " +
                " from " + tableName1 + " t1 left join " + ShiroKit.getUser().getCustomer_info() + " t2 on t1.customer_id=t2.id " +
                " left join "+ ShiroKit.getUser().getDeal_info() +" d on t1.deal_id=d.id" +
                " left join checkout_method_info t3 on t1.checkout_method_id =t3.id " +
                " where 1=1 and t1.isEarnes!=3 and !(t1.isEarnes=2 and t1.section_performance=0 and t1.hospital_performance=0) ";
        if (StringUtils.isNoneEmpty(reach)) {  //结账时间
            sql += "  and (t2.customer_name like CONCAT('%','" + reach + "','%') or t2.customer_phone like CONCAT('%','" + reach + "','%') or " +
                    " t2.wechat_number like CONCAT('%','" + reach + "','%') or t2.medical_record_number like CONCAT('%','" + reach + "','%') or " +
                    " t2.szm like CONCAT('%','" + reach + "','%')) ";
        }
        if (StringUtil.isNotEmpty(fieldTc)) {
            String fieldTcs[] = fieldTc.split(",");
            fieldTc="";
            if (fieldTcs.length == 1) {
                fieldTc = fieldTcs[0];
            } else {
                for (int i = 0; i < fieldTcs.length; i++) {
                    if (i == (fieldTcs.length - 1)) {
                        fieldTc += "'" + fieldTcs[i];
                    } else if (i == 0) {
                        fieldTc += fieldTcs[i] + "'" + ",";
                    } else {
                        fieldTc += "'" + fieldTcs[i] + "'" + ",";
                    }
                }
            }
            sql += " and (t1.tc_name in ('" + fieldTc + "') or d.tc_name in ('" + fieldTc + "') )";
        }
        if (StringUtil.isNotEmpty(customerStatus)) {
            String customerStatuss[] = customerStatus.split(",");
            customerStatus="";
            if (customerStatuss.length == 1) {
                customerStatus = customerStatuss[0];
            } else {
                for (int i = 0; i < customerStatuss.length; i++) {
                    if (i == (customerStatuss.length - 1)) {
                        customerStatus += "'" + customerStatuss[i];
                    } else if (i == 0) {
                        customerStatus += customerStatuss[i] + "'" + ",";
                    } else {
                        customerStatus += "'" + customerStatuss[i] + "'" + ",";
                    }
                }
            }
            sql += " and t2.customer_status in ('" + customerStatus + "')";
        }
        if (StringUtil.isNotEmpty(doctor)) {
            sql += " and t2.doctor = '" + doctor + "'";
        }
        if (StringUtil.isNotEmpty(startTime)) {
            sql += " and t1.recharge_time >= '" + startTime + "'";
        }
        if (StringUtil.isNotEmpty(endTime)) {
            sql += " and t1.recharge_time <= '" + endTime + "'";
        }
        sql += "  ) t1   where 1=1 ";
        if (StringUtil.isNotEmpty(checkoutMethod)) {
            String checkoutMethods[] = checkoutMethod.split(",");
            checkoutMethod="";
            if (checkoutMethods.length == 1) {
                checkoutMethod = checkoutMethods[0];
            } else {
                for (int i = 0; i < checkoutMethods.length; i++) {
                    if (i == (checkoutMethods.length - 1)) {
                        checkoutMethod += "'" + checkoutMethods[i];
                    } else if (i == 0) {
                        checkoutMethod += checkoutMethods[i] + "'" + ",";
                    } else {
                        checkoutMethod += "'" + checkoutMethods[i] + "'" + ",";
                    }
                }
            }
            sql += " and t1.checkoutMethod in ('" + checkoutMethod + "')";
        }
        sql += " order by t1.recordTime DESC limit 1;";
        Map<String, Object> result = sqlMapper.selectOne(sql.toString());
        HashMap map = new HashMap();
        if (result != null) {
            map.put("borrowAmount_sum", result.get("borrowAmount_sum"));
        } else {
            map.put("borrowAmount_sum", "0");
        }
        return map;
    }


    @RequestMapping(value = "/paymentRecordExport")
    public void reservationsExport(@Valid SearchPaymentRecordInfo searchInfo, HttpServletResponse response) {
        try {
            List<PaymentRecordInfo> list = service.getPaymentRecordExport(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 27; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("客户姓名");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("客户电话");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("客户状态");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("TC");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("结账金额");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("结账方式");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("结账时间");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("备注");
            cell.setCellStyle(style);
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                PaymentRecordInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 27; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(map.getCustomerName());
                if(ShiroKit.getUser().getPhonePrivilegesexp()==1) {
                    row.getCell(1).setCellValue(map.getCustomerPhone());
                }else{
                    row.getCell(1).setCellValue("无");
                }
                row.getCell(2).setCellValue(map.getSex());
                row.getCell(3).setCellValue(map.getCustomerAge());
                row.getCell(4).setCellValue(map.getCustomerStatus());
                row.getCell(5).setCellValue(map.getFieldTc());
                row.getCell(6).setCellValue(map.getActualAccountBalance());
                row.getCell(7).setCellValue(map.getCheckoutMethod());
                row.getCell(8).setCellValue(map.getRechargeTime());
                row.getCell(9).setCellValue(map.getRemarks());
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}